package com.example.lotterysystem.common.utils;

import com.example.lotterysystem.common.pojo.CommonResult;
import com.fasterxml.jackson.core.JacksonException;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * @auther falls_vc
 * description:
 * @date 2025/5/8  11:13
 */
public class JacksonUtil {
    /**
     * 单例
     */
    private JacksonUtil(){

    }
    private final static ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER=new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper(){
        return OBJECT_MAPPER;
    }

    // 统一处理结果和异常
    private static  <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    private static  <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }

            throw new IllegalStateException(var4);
        }
    }

    /**
     * 序列化
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object){
        return JacksonUtil.tryParse(()-> {
                return JacksonUtil.getObjectMapper().writeValueAsString(object);
            });
    }

    /**
     * 反序列化
     * @param content
     * @param classType
     * @return
     * @param <T>
     */
    public static <T> T readValue(String content,Class<T> classType){
        return JacksonUtil.tryParse(()->{
           return  JacksonUtil.getObjectMapper().readValue(content,classType);
        });
    }

    /**
     * 反序列化 List
     * @param content
     * @param classType
     * @return
     * @param <T>
     */
    public static <T> T readListValue(String content, Class<?> classType){
        JavaType javaType=JacksonUtil.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class,classType);
        return JacksonUtil.tryParse(()->{
            return  JacksonUtil.getObjectMapper().readValue(content,javaType);
        });
    }
}
